<template>
    <div>
      <h1>Received MQTT Message: {{ receivedMessage }}</h1>
    </div>
  </template>
  
  <script>
  import mqtt from 'mqtt';
  
  export default {
    data() {
      return {
        receivedMessage: '',
        mqttClient: null,
        connectUrl: `ws://139.9.138.46:8083/mqtt`,
        mqttTopic: '/test',
        mqttUsername: 'user',
        mqttPassword: 'user123'
      };
    },
    created() {
      // 初始化 MQTT 连接
      this.initMqttClient();
    },
    methods: {
      initMqttClient() {
        // 创建 MQTT 客户端，指定用户名和密码
        this.mqttClient = mqtt.connect(this.connectUrl, {
          clientId: 'mqttjs_0643a11f05',
          username: this.mqttUsername,
          password: this.mqttPassword
        });
  
        // 连接到 MQTT 服务器
        this.mqttClient.on('connect', () => {
          console.log('Connected to MQTT broker');
  
          // 订阅主题
          this.mqttClient.subscribe(this.mqttTopic, (err) => {
            if (!err) {
              console.log('Subscribed to topic:', this.mqttTopic);
            } else {
              console.error('Error subscribing to topic:', err);
            }
          });
        });
  
        // 处理接收到的消息
        this.mqttClient.on('message', (topic, message) => {
          console.log('Received message:', message.toString());
          // 更新接收到的消息
          this.receivedMessage = message.toString();
        });
  
        // 处理连接断开
        this.mqttClient.on('close', () => {
          console.log('Disconnected from MQTT broker');
        });
      }
    },
    beforeDestroy() {
      // 在组件销毁之前断开 MQTT 连接
      if (this.mqttClient) {
        this.mqttClient.end();
      }
    }
  };
  </script>